package drds.server.net.packet;

/**
 * 
 * @author 曹正辉<330937205@qq.com>
 * 
 */
public class Bytes {

	public static int readInt2(byte[] bytes, int offset) {
		int $int = bytes[offset] & 0xff;
		$int |= (bytes[++offset] & 0xff) << 8;
		return $int;
	}

	public static int readInt3(byte[] bytes, int offset) {
		int $int = bytes[offset] & 0xff;
		$int |= (bytes[++offset] & 0xff) << 8;
		$int |= (bytes[++offset] & 0xff) << 16;
		return $int;
	}

	public static long readLong4(byte[] bytes, int offset) {
		long $long = bytes[offset] & 0xff;
		$long |= (bytes[++offset] & 0xff) << 8;
		$long |= (bytes[++offset] & 0xff) << 16;
		$long |= (bytes[++offset] & 0xff) << 24;
		return $long;
	}

	public static long readLong8(byte[] bytes, int offset) {
		long $long = (long) (bytes[offset] & 0xff);
		$long |= (long) (bytes[++offset] & 0xff) << 8;
		$long |= (long) (bytes[++offset] & 0xff) << 16;
		$long |= (long) (bytes[++offset] & 0xff) << 24;
		$long |= (long) (bytes[++offset] & 0xff) << 32;
		$long |= (long) (bytes[++offset] & 0xff) << 40;
		$long |= (long) (bytes[++offset] & 0xff) << 48;
		$long |= (long) (bytes[++offset] & 0xff) << 56;
		return $long;
	}

	public static long readLength(byte[] bytes, int offset) {
		int length = bytes[offset++] & 0xff;
		switch (length) {
		case 251:
			return BytesHolder.NULL_LENGTH;
		case 252:
			return readInt2(bytes, offset);
		case 253:
			return readInt3(bytes, offset);
		case 254:
			return readLong8(bytes, offset);
		default:
			return length;
		}
	}

	public static int lengthToZero(byte[] bytes, int offset) {
		int start = offset;
		for (int i = start; i < bytes.length; i++) {
			if (bytes[i] == 0) {
				return (i - start);
			}
		}
		int remaining = bytes.length - start;
		return remaining > 0 ? remaining : 0;
	}

	public static int decodeLength(byte[] bytes) {
		int length = bytes.length;
		if (length < 251) {
			return 1 + length;
		} else if (length < 0x10000L) {
			return 3 + length;
		} else if (length < 0x1000000L) {
			return 4 + length;
		} else {
			return 9 + length;
		}
	}

	public static int decodeLength(long length) {
		if (length < 251) {
			return 1;
		} else if (length < 0x10000L) {
			return 3;
		} else if (length < 0x1000000L) {
			return 4;
		} else {
			return 9;
		}
	}

}